const { default: got } = require('got/dist/source');
const { Controller } = require('../lib/contorller');
const { userModel } = require('../lib/mongo');

const sso = got.extend({ prefixUrl: 'https://sso.oaloft.com' });

module.exports = class SsoController extends Controller {
  async login() {
    const { ctx } = this;
    try {
      const service = `${ ctx.protocol }://${ ctx.headers.host }/sso/login`;
      const { body: authInfo } = await sso.get('cas/validate', {
        searchParams: {
          service,
          ticket: ctx.query.ticket,
        },
      });
      const [success, userId] = authInfo.split('\n');
      if (success !== 'yes') {
        ctx.result.message = '认证失败';
        return;
      }
      const userInfo = await userModel.findById(userId).lean();
      if (userInfo) {
        ctx.session.user = userInfo;
        return ctx.response.redirect('/#/kv?type=dir&dc=m7&key=online-school');
      } else {
        return ctx.result.message = '无权限';
      }
    } catch (error) {
      this.log.error(error);
      ctx.result.message = error?.message;
    }
  }

  async getUserInfo() {
    this.ctx.result.info = this.ctx.session.user;
    this.ctx.result.success = true;
  }

  async logout() {
    const { ctx } = this;
    try {
      ctx.session = null;
      this.ctx.result.success = true;
    } catch (error) {
      this.log.error(error);
      ctx.result.message = error?.message;
    }
  }
};
